#pragma semicolon 1
#pragma newdecls required

#include <sourcemod>
#include <left4dhooks>

#define PLUGIN_VERSION "1.0"
#define UPDATE_INTERVAL 0.1

public Plugin myinfo =
{
	name = "l4d2_auto_hide_target_display",
	author = "豆瓣酱な",
	description = "生还者或特感可以看敌人名字.",
	version = PLUGIN_VERSION,
	url = "https://gitee.com/sweet-and-sour-bombs/adfvsdsd"
};

int g_iLastTarget[MAXPLAYERS + 1];

public void OnPluginStart()
{
    HookEvent("round_start", Event_RoundReset);
    CreateTimer(UPDATE_INTERVAL, Timer_UpdateDisplay, _, TIMER_REPEAT);
}

public void OnClientPutInServer(int client)
{
    g_iLastTarget[client] = -1;
}

public Action Event_RoundReset(Event event, const char[] name, bool dontBroadcast)
{
    for (int i = 1; i <= MaxClients; i++) 
    g_iLastTarget[i] = -1;
    return Plugin_Continue;
}

public Action Timer_UpdateDisplay(Handle timer)
{
    for (int client = 1; client <= MaxClients; client++)
    {
        if (IsClientInGame(client) && IsPlayerAlive(client) && !IsFakeClient(client))
        {
            int target = GetClientAimTarget(client, true);
            
            if (target != g_iLastTarget[client])
            {
                g_iLastTarget[client] = target;
                
                if (IsValidTarget(client, target))
                {
                    char name[MAX_NAME_LENGTH];
                    GetClientName(target, name, sizeof(name));
                    if (IsFakeClient(target))
                    Format(name, sizeof(name), "%s [BOT]", name);
                    
                    PrintHintText(client, name);
                }
            }
        }
    }
    return Plugin_Continue;
}

bool IsValidTarget(int viewer, int target)
{
    if (target <= 0 || !IsClientInGame(target) || !IsPlayerAlive(target))
    return false;
    
    int viewerTeam = GetClientTeam(viewer);
    int targetTeam = GetClientTeam(target);
    return (viewerTeam == 2 && targetTeam == 3) || (viewerTeam == 3 && targetTeam == 2);
}

public void OnClientDisconnect(int client)
{
    g_iLastTarget[client] = -1;
}